package com.lfs.feishu.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lark.oapi.Client;
import com.lfs.feishu.domain.request.BatchSendRequest;
import com.lfs.feishu.service.UserInfoService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@AllArgsConstructor
@RestController
@RequestMapping("/feishu/batch")
@Slf4j
public class FeishuBatchSendController {
    private static final String BATCH_SEND_URL = "https://open.feishu.cn/open-apis/message/v4/batch_send/";


    private final Configuration freemarkerConfig;
    private final RestTemplate restTemplate;
    private final Client client;

    @Autowired
    UserInfoService userInfoService;


    // 模板数据
    private static final Map<String, Object> data = new HashMap<>(){{
        put("title", "何意味");
        put("contentList", List.of(
                Map.of("title", "姓名", "content", "神秘人"),
                Map.of("title", "身份", "content", "老资历"),
                Map.of("title", "电话", "content", "1145141919810")
        ));

        put("topPic", "img_v3_02qi_5e57dca8-64f2-4c2c-8972-0b40d95fcaeg");
        put("subtitle", "何意味！何意味...");
        put("conclusion", "何意味？！");
        put("buttonText", "去看看吧");
        put("address", Map.of(
                "pc_url", "https://www.baidu.com",
                "android_url", "https://open.feishu.cn/",
                "ios_url", "https://open.feishu.cn/",
                "default_url", "https://zhuanlan.zhihu.com/"
        ));
    }};


    @PostMapping("/advancedSend")
    public ResponseEntity<String> batchSendCard(@RequestBody BatchSendRequest request) throws Exception {
        String url = request.getUrl();


        // 1. 获取 tenant_access_token
        String tenantAccessToken = userInfoService.getAppToken();

        // 2. 渲染卡片模板
        Template template = freemarkerConfig.getTemplate("horizontal_card_template.ftl");
        StringWriter writer = new StringWriter();
        request.setTemplateVariables(data);
        template.process(request.getTemplateVariables(), writer);
        String cardJson = writer.toString();

        // 3. 构建飞书API请求体
        Map<String, Object> apiRequestBody = new HashMap<>();
        apiRequestBody.put("department_ids", request.getDepartmentIds());
        apiRequestBody.put("open_ids", request.getOpenIds());
        apiRequestBody.put("user_ids", request.getUserIds());
        apiRequestBody.put("union_ids", request.getUnionIds());
        apiRequestBody.put("msg_type", "interactive");


        // 使用ObjectMapper将卡片JSON字符串解析为Map对象
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> cardObject = objectMapper.readValue(cardJson, Map.class);
        apiRequestBody.put("card", cardObject);

        // 签名
        String sign = request.getSign();
        if (StringUtils.isNotEmpty(sign)) {
            apiRequestBody.put("sign", sign);
            apiRequestBody.put("timestamp", request.getTimestamp());
        }


        // 4. 设置HTTP Headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(tenantAccessToken);

        // 5. 发送HTTP请求
        HttpEntity<String> httpEntity = new HttpEntity<>(JSON.toJSONString(apiRequestBody), headers);
        ResponseEntity<String> response = restTemplate.postForEntity(StringUtils.isEmpty(url)? BATCH_SEND_URL: url, httpEntity, String.class);

        // 6. 记录并返回响应
        log.info("Feishu API Response: {}", response.getBody());

        return response;
    }
}
